package com.acxy.ants.core;

import com.acxy.ants.common.kit.StrKit;
import com.acxy.ants.core.kit.LogKit;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.util.resource.Resource;
import org.eclipse.jetty.webapp.WebAppContext;

import javax.servlet.DispatcherType;
import java.util.EnumSet;


/**
 * @author MrShun
 * @version 1.0
 * @Date 2017-06-12
 */
public class Jetty {

    /**
     * 配置Jetty启动
     * @param target 目标资源目录
     * @param port 端口
     * @param name 项目访问名称
     */
    public static void start(String target, Integer port, String name){
        if(port == null) port = 8080;
        if (port < 0 || port > 65535) {
            throw new IllegalArgumentException("Invalid port of web server: " + port);
        }
        if (name.isEmpty()) {
            throw new IllegalStateException("Invalid name of web server: " + name);
        }

        name = StrKit.setInitial(name, "/");

        Server server = new Server();

        Connector connector = new SelectChannelConnector();
        connector.setPort(port);

        server.addConnector(connector);

        WebAppContext webAppContext = null;
        if(target != null){
            webAppContext = new WebAppContext(target, name);
            webAppContext.setDescriptor(target + "/WEB-INF/web.xml");
        }else{
            webAppContext = new WebAppContext();
            webAppContext.setContextPath(name);
            webAppContext.setBaseResource(Resource.newClassPathResource(""));
        }

        webAppContext.setClassLoader(Thread.currentThread().getContextClassLoader());
        webAppContext.setThrowUnavailableOnStartupException(true);	// 在启动过程中允许抛出异常终止启动并退出 JVM
        webAppContext.setConfigurationDiscovered(true);
        webAppContext.setParentLoaderPriority(true);
        server.setHandler(webAppContext);


        //设置加入Ants过滤器
        FilterHolder filterHolder = new FilterHolder(new AntsFilter());
        webAppContext.addFilter(filterHolder, "/*", EnumSet.allOf(DispatcherType.class));

        try {
            server.start();
            LogKit.info(Jetty.class, "Jetty is start success!");
            server.join();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void start(String target, String name){
        start(target, null, name);
    }

    public static void start(Integer port, String name){
        start(null, port, name);
    }
}
